package cn.zqh.gateway.config;


import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;


import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * @Author: zqh
 * @Date: 2023-02-19-15:34
 * @Description: as$
 */
@Configuration
@EnableConfigurationProperties(GlobalCorsProperties.class)
public class CorsConfig {



    @Order(Ordered.HIGHEST_PRECEDENCE)
    @RefreshScope
    @Bean
    public CorsWebFilter corsWebFilter(GlobalCorsProperties globalCorsProperties){
//        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(new PathPatternParser());
//        globalCorsProperties.getCorsConfigurations().forEach((k,v)->urlBasedCorsConfigurationSource.registerCorsConfiguration(k,v));
//        return new CorsWebFilter(urlBasedCorsConfigurationSource);
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOrigin("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}
